/*
 * Copyright (c) 2010 CCX(China) Co.,Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * CCX(China) Co.,Ltd. ("Confidential Information").
 * It may not be copied or reproduced in any manner without the express 
 * written permission of CCX(China) Co.,Ltd.
 *
 * Author: zhnb
 * Date: 2011-7-29 下午03:33:00
 */
package com.number.operator;

import java.io.Serializable;

import Ice.ObjectPrx;

import com.number.bean.Bond;
import com.number.bond.BondI;
import com.number.bond.ObjectFactory4Bond;
import com.number.except.UGenericException;

public class SendObjectAsParamClient implements Serializable {

    private static final long serialVersionUID = 7786343903829853789L;
    
    public static void main(String[] args) {
        Bond bond = new BondI();
        bond.setbCode("-600006");
        bond.setbName("-青岛啤酒");
        
        new SendObjectAsParamClient().sendObject(bond);
    }
    
    public void sendObject(Bond bond){
        try {
            // 防下文this.ic未被初始化
            SendObjectAsParamPrx prx = this.getOwnPrx();
            // 添加自定义类
            Ice.ObjectFactory factory = new ObjectFactory4Bond();
            this.ic.addObjectFactory(factory, com.number.bond.BondI.ice_staticId());
            
            prx.send(bond);
            
            // 回显。并不修改客户方传递的bond对象（值传递）
            System.out.println(bond.bCode + bond.bName);
            
        } catch (UGenericException e) {
            e.printStackTrace();
        }
    }

    // =========以<下>为私有方法，提供ICE支撑。=========
    // 获取服务端提供的代理
    private SendObjectAsParamPrx sendObjectAsParamPrx = null;

    // Ice通讯员（为回收资源时，方便自动回收）
    private Ice.Communicator ic = null;

    // GC回收时，自动销毁Ice.Communicator。
    @Override
    protected void finalize() throws Throwable {
        if (this.ic != null) {
            ic.destroy();
        }
        super.finalize();
    }

    /**
     * 获取代理
     * 
     * @return 本类的代理
     */
    private SendObjectAsParamPrx getOwnPrx() throws UGenericException {

        // 代理为空时，自动获取代理。
        if (this.sendObjectAsParamPrx == null) {
            // 环境为空时，初始化环境
            if (this.ic == null) {
                // 1, 初始化环境
                ic = Ice.Util.initialize();
            }
            // 2, 创建代理基类对象
            String str = "SendObjectAsParamUID:default -h 127.0.0.1 -p 9999";
            
            ObjectPrx objPrx = this.ic.stringToProxy(str);
            // 3, 获取代理
            this.sendObjectAsParamPrx = SendObjectAsParamPrxHelper.checkedCast(objPrx);

            // 4, 测试是否可用，不可用时抛出异常。
            if (this.sendObjectAsParamPrx == null) {
                throw new UGenericException(str + ", request proxy faild.");
            }
        }
        return this.sendObjectAsParamPrx;
    }
    // =========以<上>为私有方法，提供ICE支撑。=========
}
